<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
  <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
  <title>小城趣播</title>
  <link rel="stylesheet" type="text/css" href="../css/api.css" />
  <link rel="stylesheet" type="text/css" href="../css/common.css" />
</head>

<body>
  <div id="app" v-cloak>
    <div class="wrap flex-wrap flex-vertical">
      <header id="header">
        <div v-if="index == 0" class="header-wrap">
          <div class="header-title">{{frames[index].title}}</div>
          <!-- <div class="header-right" @click="publish">
            <i class="iconfont icon-font-add1"></i>
          </div> -->
        </div>
        <!-- <div v-if="index == 0" class="header-wrap">
          <div class="header-left search-wrap" @click="openWinSearch">
            <i class="iconfont icon-search"></i>
          </div>
          <div class="nav">
            <a href="javascript:;" :class="indexHome==0?'active':''" tapmode @click="setHomeFrame(0)" class="nav-left">首页</a>
            <a href="javascript:;" :class="indexHome==1?'active':''" tapmode @click="setHomeFrame(1)" class="nav-left">排行榜</a>
          </div>
          <div class="header-right" @click="openNearby">
            <i class="icon icon-nearby"></i>
          </div>
        </div> -->
        <div v-if="index == 1" class="header-wrap live-wrap">
          <div class="live-search">
            <i class="icon icon-search1"></i>
            <input class="search-input" type="text" v-model="keyword" placeholder="请输入房间号" @keyup.enter="search">
          </div>
          <div @click="openVideoLiveAdd" class="header-right">
            <i class="icon icon-add"></i>
          </div>
        </div>
        <div v-if="index == 2" class="header-wrap">
          <div class="nav">
            <a href="javascript:;" :class="indexDynamic==0?'active':''" tapmode @click="setDynamic(0)" class="nav-left">关注</a>
            <a href="javascript:;" :class="indexDynamic==1?'active':''" tapmode @click="setDynamic(1)" class="nav-left">推荐</a>
            <a href="javascript:;" :class="indexDynamic==2?'active':''" tapmode @click="setDynamic(2)" class="nav-right">附近</a>
          </div>
          <div @click="publish" class="header-right">
            <i class="iconfont icon-font-add1"></i>
          </div>
        </div>
        <div v-if="index == 3" class="header-wrap">
          <div class="header-title">{{frames[index].title}}</div>
        </div>
        <div v-if="index == 4" class="header-wrap ">
          <div class="header-title">{{frames[index].title}}</div>
          <div @click="edit" class="header-right">
            <i class="iconfont icon-bianji"></i>
          </div>
        </div>
      </header>
      <div id="main" class="main flex-con"></div>
      <div id="footer">
        <ul class="flex-wrap">
          <li v-for="(item, i) in frames" :key="i" tapmode="hover" @click="tabBarSelected(i);" :class="['flex-con', index == i ? 'active' : '']">
            <i :class="['icon', 'icon-tab' + i]"></i>
            <div class="title">{{item.title}}</div>
            <span v-if="i == 3 && messageBadge" class="messageBadge"></span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</body>

</html>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/vue.js"></script>
<script type="text/javascript" src="../script/common.js"></script>
<script type="text/javascript">
  var app, wx, qq;
  apiready = function () {
    $api.fixStatusBar($api.dom('#header'));
    wx = api.require('wx');
    qq = api.require('QQPlus');
    api.setStatusBarStyle({
      style: 'light',
    });
    app = new Vue({
      el: '#app',
      data: {
        appName: api.appName,
        userInfo: {
          name: '',
          avatar: '',
          signature: '',
          occupation: '',
          background: [],
          level: '1',
          certification: '1',
        },
        frames: [{
          name: 'video',
          title: '短视频',
          url: 'video.html',
          bgColor: 'rgba(0,0,0,.2)',
          bounces: true
        }, {
          name: 'live',
          title: '直播间',
          url: 'live.html',
          bgColor: 'rgba(0,0,0,.2)',
          bounces: true
        }, {
          // name: 'video',
          title: '社区',
          // url: 'video.html',
          bgColor: 'rgba(0,0,0,.2)',
          bounces: true
        }, {
          name: 'home',
          title: '一对一',
          url: 'home.html',
          bgColor: 'rgba(0,0,0,.2)',
          bounces: true
        }, {
          name: 'my',
          title: '我的',
          url: 'my.html',
          bgColor: 'rgba(0,0,0,.2)',
          bounces: true,
        }],
        index: !!$api.getStorage('index') ? $api.getStorage('index') : 0,
        curHomeBackTriggerTimes: 1,
        maxHomeBackTriggerTimes: 2,
        messageBadge: false,
        indexDynamic: 1,
        keyword: '',
        imgBrowser: false,
        shareTitle: '',
        shareContent: '',
        shareUrl: '',
        shareImage: '',
        shareImageQQ: '',
      },
      created: function () {
        var _this = this;
        this.androidFinishApp();
        this.checkUpdate();
        api.addEventListener({
          name: 'cleanMessageBadge'
        }, function (ret, err) {
          _this.messageBadge = false;
        });
        api.addEventListener({
          name: 'openImgBrowser'
        }, function(ret, err){
          _this.imgBrowser = ret.value.imgBrowser;
        });
      },
      mounted: function () {
        this.funIniGroup();
        this.openDynamicFrameGroup();
        if (!!$api.getStorage('token')) {
          this.rongConnect();
        }
        this.getShareIndex();
        this.getUserIndex();
      },
      methods: {
        // 检查app版本更新 
        checkUpdate: function () {
          var mam = api.require('mam');
          mam.checkUpdate(function (ret, err) {
            if (ret) {
              var result = ret.result;
              if (result.update) {
                var str = '新版本号:' + result.version + ';\n更新内容:\n' + result.updateTip + ';\n发布时间:' + result.time;
                if (result.closed) {
                  api.alert({
                    title: '有新版本更新',
                    msg: str,
                  }, function (ret, err) {
                    if (ret.buttonIndex == 1) {
                      if (api.systemType == "android") {
                        api.download({
                          url: result.source,
                          report: true
                        }, function (ret, err) {
                          if (ret && 0 == ret.state) {
                            api.showProgress({
                              title: ret.percent + "%",
                              text: ''
                            });
                          }
                          if (ret && 1 == ret.state) { /* 下载完成 */
                            api.hideProgress();
                            api.installApp({
                              appUri: ret.savePath
                            });
                          }
                        });
                      }
                      if (api.systemType == "ios") {
                        api.installApp({
                          appUri: result.source
                        });
                      }
                    }
                  });
                } else {
                  api.confirm({
                    title: '有新版本推送，是否下载安装',
                    msg: str,
                    buttons: ['确定', '下次再说']
                  }, function (ret, err) {
                    if (ret.buttonIndex == 1) {
                      if (api.systemType == "android") {
                        api.download({
                          url: result.source,
                          report: true
                        }, function (ret, err) {
                          if (ret && 0 == ret.state) {
                            api.showProgress({
                              title: ret.percent + "%",
                              text: ''
                            });
                          }
                          if (ret && 1 == ret.state) { /* 下载完成 */
                            api.hideProgress();
                            api.installApp({
                              appUri: ret.savePath
                            });
                          }
                        });
                      }
                      if (api.systemType == "ios") {
                        api.installApp({
                          appUri: result.source
                        });
                      }
                    }
                  });
                }
              } else {
                if (result.closed) {
                  // 无更新，强制关闭
                  api.alert({
                    title: '无新的版本',
                    msg: '应用已强制关闭',
                  }, function (ret, err) {
                    if (ret.buttonIndex == 1) {
                      api.closeWidget({
                        id: api.appId,
                        silent: true
                      });
                    }
                  });
                }
              }
            }
          });
        },

        // 点击返回两次退出应用
        androidFinishApp: function () {
          var _this = this;
          api.addEventListener({
            name: 'keyback'
          }, function (ret, err) {
            if (_this.imgBrowser) {
              api.sendEvent({
                name: 'closeImgBrowser',
                extra: {
                  key: 'value'
                }
              });
              _this.imgBrowser = false;
              return false;
            }
            if (_this.curHomeBackTriggerTimes === _this.maxHomeBackTriggerTimes) {
              api.closeWidget({
                id: api.appId,
                silent: true
              });
            } else {
              api.toast({
                msg: api.appName + '：再按一次退出应用'
              })
            }
            _this.curHomeBackTriggerTimes++;
            setTimeout(function () {
              _this.curHomeBackTriggerTimes--;
            }, 2000);
          });
        },

        funIniGroup: function () {
          api.openFrameGroup({
            name: 'group',
            scrollEnabled: false,
            rect: {
              x: 0,
              y: $api.dom('#header').offsetHeight,
              w: api.winWidth,
              h: $api.dom('#main').offsetHeight
            },
            index: this.index,
            frames: this.frames,
            preload: 0
          }, function (ret, err) {});
        },

        tabBarSelected: function (index) {
          var _this = this;
          if (index == 2) {
            api.setFrameGroupAttr({
              name: 'dynamicGroup',
              hidden: false
            });
          } else {
            api.setFrameGroupAttr({
              name: 'dynamicGroup',
              hidden: true
            });
          }
          if (index == _this.index) {
            return false;
          } else {
            _this.index = index;
            $api.setStorage('index', index);
            api.setFrameGroupIndex({
              name: 'group',
              index: index
            });
          }
        },

        openDynamicFrameGroup: function () {
          var _this = this;
          api.openFrameGroup({
            name: 'dynamicGroup',
            rect: {
              x: 0,
              y: $api.dom('#header').offsetHeight,
              w: api.winWidth,
              h: $api.dom('#main').offsetHeight
            },
            frames: [{
              name: 'dynamic_follow',
              url: 'dynamic_follow.html',
              bgColor: '#fff'
            }, {
              name: 'dynamic',
              url: 'dynamic.html',
              bgColor: '#fff'
            }, {
              name: 'dynamic_local',
              url: 'dynamic_local.html',
              bgColor: '#fff'
            }],
            index: _this.indexDynamic
          }, function (ret, err) {
            _this.indexDynamic = ret.index;
          })
          if (_this.index != 2) {
            api.setFrameGroupAttr({
              name: 'dynamicGroup',
              hidden: true
            });
          }
        },

        // 首页点击切换Tab
        setDynamic: function (index) {
          api.setFrameGroupIndex({
            name: 'dynamicGroup',
            index: index
          })
        },

        // 连接融云IM 设置接收消息监听器
        rongConnect: function () {
          var _this = this;
          rong = api.require('rongCloud2');
          rong.init(function (ret, err) {
            if (ret.status == 'success') {
              rong.connect({
                token: $api.getStorage('token')
              }, function (ret, err) {
                if (err) {
                  switch (err.code) {
                    case 31003:
                      api.toast({
                        msg: '服务器不可用'
                      });
                      break;
                    case 31004:
                      api.toast({
                        msg: '错误的令牌（Token）'
                      });
                      break;
                    case 31002:
                      api.toast({
                        msg: '错误的 AppKey'
                      });
                      break;
                    case 33002:
                      api.toast({
                        msg: '服务端数据库错误'
                      });
                      break;
                    case 31000:
                      api.toast({
                        msg: '服务器超时'
                      });
                      break;
                    default:
                      break;
                  }
                }
				
                if (ret.status == 'success') {
                  rong.setOnReceiveMessageListener(function (ret, err) {
                    if (ret.result.message.objectName == 'RC:CmdMsg') {
                      if (ret.result.message.content.name == 'loginOut') {
                        api.alert({
                          title: '警告',
                          msg: '此账号已违规!'
                        }, function (ret, err) {
                          if (ret.buttonIndex == 1) {
                            api.ajax({
                              url: baseUrl + 'oauth/logout',
                              method: 'get',
                              headers: {
                                token: $api.getStorage('deviceToken')
                              },
                              data: {
                                values: {
                                  uid: $api.getStorage('uid')
                                },
                              }
                            }, function (ret, err) {
                              if (ret && ret.status == 200) {
                                $api.rmStorage('uid');
                                $api.rmStorage('uname');
                                $api.rmStorage('uavatar');
                                $api.rmStorage('umobile');
                                $api.rmStorage('token');
                                $api.rmStorage('index');
                                rong.disconnect({
                                  isReceivePush: false
                                }, function (ret, err) {});
                                api.closeToWin({
                                  name: 'root'
                                });
                              }
                            });
                          }
                        });
                      }
                      if (ret.result.message.content.name == 'voiceCall' || ret.result.message.content
                        .name == 'videoCall') {
                        if ((ret.result.message.receivedTime - ret.result.message.sentTime) > 30000) {
                          api.toast({
                            msg: '您有一个未接电话',
                            duration: 3000,
                            location: 'bottom'
                          });
                          $api.setStorage('index', 3);
                          api.setFrameGroupIndex({
                            name: 'group',
                            index: 3
                          });
                          return false;
                        }
                        api.closeWin({
                          name: 'call'
                        });
                        // 接到语音通话邀请
                        api.openWin({
                          name: 'answer',
                          url: 'answer1.html',
                          slidBackEnabled: false,
                          pageParam: ret.result.message.content
                        });
                      }
                      if (ret.result.message.content.name == 'hangUp') {
                        // 挂断
                        api.sendEvent({
                          name: 'hangUp',
                          extra: ret
                        });
                      }
                      if (ret.result.message.content.name == 'answer') {
                        // 接听
                        api.sendEvent({
                          name: 'answer',
                          extra: ret
                        });
                      }
                      if (ret.result.message.content.name == 'give_gift_notice_private') {
                        // 1v1赠送礼物显示通知
                        if ((ret.result.message.receivedTime - ret.result.message.sentTime) > 30000) {
                          api.toast({
                            msg: '您收到礼物了',
                            duration: 2000,
                            location: 'bottom'
                          });
                          $api.setStorage('index', 3);
                          api.setFrameGroupIndex({
                            name: 'group',
                            index: 3
                          });
                          return false;
                        }
                        api.sendEvent({
                          name: 'give_gift_notice_private',
                          extra: ret
                        });
                      }
                    } else {
                      _this.messageBadge = true;
                      api.sendEvent({
                        name: 'updateConversationList',
                        extra: ret
                      });
                      api.sendEvent({
                        name: 'updateIM',
                        extra: ret
                      })
                    }
                    // api.alert({
                    // 	title: 'setOnReceiveMessageListener',
                    // 	msg: JSON.stringify(ret)
                    // })
                  })
                }
              });
            } else {
              if (err.code == -10002) {
                api.toast({
                  msg: 'appKey参数错误'
                });
              }
            }
          });
        },

        openWinSearch: function () {
          api.openWin({
            name: 'search',
            url: 'search.html',
            slidBackEnabled: false
          });
        },

        openNearby: function () {
          api.openWin({
            name: 'nearby',
            url: 'nearby.html',
            bounces: false,
            pageParam: {
              key: 'value'
            }
          });
        },

        openShare: function () {
          var _this = this;
          var dialogBox = api.require('dialogBox');
          dialogBox.actionMenu({
            rect: {
              h: 100
            },
            items: [{
              text: '微信好友',
              icon: 'widget://image/circular-WeChat.png'
            }, {
              text: '微信朋友圈',
              icon: 'widget://image/circle-friend.png'
            }],
            styles: {
              bg: '#FFF',
              column: 2,
              itemText: {
                color: '#000',
                size: 14,
                marginT: 5
              },
              itemIcon: {
                size: 50
              }
            },
            tapClose: true
          }, function (ret) {
            if (ret.index == 0) {
              wx.shareWebpage({
                scene: 'session',
                title: _this.shareTitle,
                description: _this.shareContent,
                thumb: _this.shareImage,
                contentUrl: _this.shareUrl
              }, function (ret, err) {
                _this.closdialg();
                if (ret.status) {
                  api.toast({
                    msg: '分享成功'
                  });
                } else {
                  api.toast({
                    msg: '分享失败'
                  });
                }
              });
            }
            if (ret.index == 1) {
              wx.shareWebpage({
                scene: 'timeline',
                title: _this.shareTitle,
                description: _this.shareContent,
                thumb: _this.shareImage,
                contentUrl: _this.shareUrl
              }, function (ret, err) {
                _this.closdialg();
                if (ret.status) {
                  api.toast({
                    msg: '分享成功'
                  });
                } else {
                  api.toast({
                    msg: '分享失败'
                  });
                }
              });
            }
            if (ret.index == 2) {
              qq.shareNews({
                type: 'QZone',
                url: _this.shareUrl,
                title: _this.shareTitle,
                description: _this.shareContent,
                imgUrl: _this.shareImageQQ
              }, function (ret, err) {
                _this.closdialg();
                if (ret.status) {
                  api.toast({
                    msg: '分享成功'
                  });
                } else {
                  api.toast({
                    msg: '分享失败'
                  });
                }
              });
            }
            if (ret.index == 3) {
              qq.shareNews({
                type: 'QFriend',
                url: _this.shareUrl,
                title: _this.shareTitle,
                description: _this.shareContent,
                imgUrl: _this.shareImageQQ
              }, function (ret, err) {
                _this.closdialg();
                if (ret.status) {
                  api.toast({
                    msg: '分享成功'
                  });
                } else {
                  api.toast({
                    msg: '分享失败'
                  });
                }
              });
            }
          });
        },

        getShareIndex: function () {
          var _this = this;
          api.ajax({
            url: baseUrl + 'share/index',
            method: 'get',
            headers: {
              token: $api.getStorage('deviceToken')
            },
            data: {
              values: {
                uid: $api.getStorage('uid'),
                type: 'spread'
              },
            }
          }, function (ret, err) {
            if (ret.status == 200) {
              _this.shareTitle = ret.data.title;
              _this.shareContent = ret.data.content;
              _this.shareUrl = ret.data.url + '?channel=' + $api.getStorage('channel') + '&tuid=' + $api.getStorage('uid');
              _this.shareImage = ret.data.image;
              _this.shareImageQQ = ret.data.image;
            }
          })
        },

        closdialg: function () {
          var dialogBox = api.require('dialogBox');
          dialogBox.close({
            dialogName: 'actionMenu'
          });
        },

        //发表动态
        publish: function () {
          var _this = this;
          // if (_this.userInfo.certification == '0') {
					// 	api.alert({
					// 		title: '提示', 
					// 		msg: '您还未认证，请认证之后发布动态'
					// 	}, function (ret) {
					// 		if (ret.buttonIndex == 1) {
					// 			api.openWin({
					// 				name: 'my_auth',
					// 				url: 'my_auth.html',
					// 				bounces: false,
					// 				pageParam: _this.userInfo
					// 			});
					// 		}
					// 	});
					// 	return false;
          // }
					// if (_this.userInfo.certification == '2') {
					// 	api.alert({
					// 		title: '提示', 
					// 		msg: '认证中，请耐心等待'
					// 	});
					// 	return false;
          // }
          api.openWin({
            name: 'dynamic_post',
            url: 'dynamic_post.html',
            slidBackEnabled: false
          })
        },

        search: function () {
          api.sendEvent({
            name: 'live_search',
            extra: {
              keyword: this.keyword
            }
          });
        },

        // 创建直播间
        openVideoLiveAdd: function () {
          api.sendEvent({
            name: 'openVideoLiveAdd',
            extra: {
              key: 'value'
            }
          });
        },
        
        edit: function () {
          api.openWin({
            name: 'edit',
            url: 'edit.html',
            slidBackEnabled: false
          });
        },
       
        getUserIndex: function () {
          var _this = this;
          api.ajax({
            url: baseUrl + 'user/index',
            method: 'get',
            headers: {
              token: $api.getStorage('deviceToken')
            },
            data: {
              values: {
                uid: $api.getStorage('uid'),
              },
            }
          }, function (ret, err) {
            if (ret.status == 200) {
              _this.userInfo = ret.data;
            }
          })
        },
      },
    })
  }
</script>